/******************************* 按钮权限守卫 **********************************/
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core';

@Injectable()
export class PermissionGuard implements CanActivate {
  constructor (
    private reflector:Reflector
  ){}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const req = context.switchToHttp().getRequest();
    const perm = this.reflector.getAllAndOverride('permission',[context.getClass(),context.getHandler()])
    if(!perm) return true
    return this.hasPermisssion(perm,req.user.permissions);
  }
/**
 * 判断是否具有权限
 * @param perm 
 * @param perms 
 * @returns 
 */
  hasPermisssion(perm:string,perms:string[]) {
    const allPerm = "*:*:*"
    let flag1 = perms.includes(allPerm)
    let flag2 = perms.some(k => k === perm)
    return flag1 || flag2
  } 
}
